import { useState, useEffect, useCallback } from 'react';
import { format } from 'date-fns';
import { CalendarDay, TodoItem } from '../types';
import { calendarDB } from '../db/operations';
import { getLunarDate, getFortune } from '../utils/lunarCalendar';

export function useCalendarData() {
  const [calendarData, setCalendarData] = useState<Record<string, CalendarDay>>({});

  // Load all calendar data on mount
  useEffect(() => {
    const loadData = async () => {
      try {
        const days = await calendarDB.getAllDays();
        const dataMap: Record<string, CalendarDay> = {};
        
        days.forEach(day => {
          dataMap[day.dateStr] = {
            date: new Date(day.dateStr),
            todos: day.todos,
            dayInfo: day.dayInfo
          };
        });
        
        setCalendarData(dataMap);
      } catch (error) {
        console.error('Failed to load calendar data:', error);
      }
    };

    loadData();
  }, []);

  const saveDay = useCallback(async (date: Date, data: CalendarDay) => {
    const dateStr = format(date, 'yyyy-MM-dd');
    try {
      await calendarDB.saveDay({
        dateStr,
        todos: data.todos,
        dayInfo: data.dayInfo
      });
    } catch (error) {
      console.error('Failed to save day:', error);
    }
  }, []);

  const addTodo = useCallback(async (date: Date, content: string) => {
    const dateStr = format(date, 'yyyy-MM-dd');
    const newTodo: TodoItem = {
      id: crypto.randomUUID(),
      content,
      completed: false,
      date: dateStr
    };

    const currentDay = calendarData[dateStr] || {
      date,
      todos: [],
      dayInfo: {
        lunar: getLunarDate(date),
        fortune: getFortune(date)
      }
    };

    const updatedDay = {
      ...currentDay,
      todos: [...currentDay.todos, newTodo]
    };

    await saveDay(date, updatedDay);
    setCalendarData(prev => ({
      ...prev,
      [dateStr]: updatedDay
    }));
  }, [calendarData, saveDay]);

  const toggleTodo = useCallback(async (date: Date, todoId: string) => {
    const dateStr = format(date, 'yyyy-MM-dd');
    const currentDay = calendarData[dateStr];
    if (!currentDay) return;

    const updatedDay = {
      ...currentDay,
      todos: currentDay.todos.map(todo =>
        todo.id === todoId ? { ...todo, completed: !todo.completed } : todo
      )
    };

    await saveDay(date, updatedDay);
    setCalendarData(prev => ({
      ...prev,
      [dateStr]: updatedDay
    }));
  }, [calendarData, saveDay]);

  const deleteTodo = useCallback(async (date: Date, todoId: string) => {
    const dateStr = format(date, 'yyyy-MM-dd');
    const currentDay = calendarData[dateStr];
    if (!currentDay) return;

    const updatedDay = {
      ...currentDay,
      todos: currentDay.todos.filter(todo => todo.id !== todoId)
    };

    await saveDay(date, updatedDay);
    setCalendarData(prev => ({
      ...prev,
      [dateStr]: updatedDay
    }));
  }, [calendarData, saveDay]);

  return {
    calendarData,
    addTodo,
    toggleTodo,
    deleteTodo
  };
}